import store from "../vuex";

// 统一放行
let withList = [
    200,
    1
]

// 统一拦截
let blackList = [
    -300,
]

//过滤列表  codeRule验证用字符串  type类型  massage提示消息  callBack验证回调
let filterList = [
    // 统一放行
    {
        codeRule: (code) => withList.indexOf(code) >= 0,
        type: 'pass',
        callBack (response) {
            console.log(response)
        }
    },
    // 统一拦截
    {
        codeRule: (code) => blackList.indexOf(code) >= 0,
        type: 'fail',
        massage (msg) {
            return msg
        },
        callBack (response) {
            console.log(response)
            store.commit('logout')
        }
    },
    {
        codeRule: (code) => code != 200,
        type: 'fail',
        massage (msg) {
            return msg
        },
        callBack (response) {
            console.log(response)
        }
    }
]




//回调拦截
export default (response) => {
    // Do something with response data
    if (!response.data.meta) {
        return response.data
    } else {

        for (let i = 0; i < filterList.length; i++) {
            let item = filterList[i]
            if ( item.codeRule(response.data.meta.code) ) {
                if (item.type == 'pass') {
                    if (item.callBack) {
                        item.callBack(response)
                    }
                    return response.data.data;
                } else {
                    store.commit('setAlert', {
                        show: true,
                        massage: item.massage(response.data.meta.msg),
                        type: 'error',
                        time: 2,
                    })
                    if (item.callBack) {
                        item.callBack(response)
                    }
                    return Promise.reject(response.data.meta.msg)
                }

            }
        }

    }

}

